<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/3/9
 * Time: 10:57
 */

namespace app\api\controller\v1;

use app\api\controller\Fun;
use app\api\repository\UserBalanceRespository;
use app\api\service\BaiduMapService;
use app\api\service\FoundService;
use app\api\service\ShaohuoOrderService;
use app\api\service\ShippingService;
use app\common\Model\Order;
use app\common\Model\OrderActionShaohuo;
use app\common\Model\OrderInfoShaohuo;
use app\common\Model\User;
use app\common\Model\UserShaohuo;
use app\common\Model\UserShaohuoFuncs;
use app\common\Server\Redis;
use think\Db;
use think\exception\ErrorException;

/**
 * @title 捎货人接口V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class Shipping extends Auth
{
    static public $validate = [
        'takeOrder' => [
            'base' => [
                'order_id' => 'order_id',
                'app_name' => 'app_name'
            ]
        ],
        'pickupOrder' => [
            'base' => [
                'order_id' => 'order_id',
                'app_name' => 'app_name'
            ]
        ],
        'sendtoOrder' => [
            'base' => [
                'order_id' => 'order_id',
                'app_name' => 'app_name'
            ]
        ],
        'changeFuncStatus' => [
            'base' => [
                'fc_id' => 'fc_id',
                'user_status' => 'user_status'
            ]
        ],
        'saveLocate' => [
            'base' => [
                'lat' => 'lat',
                'lng' => 'lng'
            ]
        ],
        'orderList' => [
            'base' => [
                'lat' => 'lat',
                'lng' => 'lng'
            ]
        ],
        'confirmServe' => [
            'base' => [
                'order_id' => 'order_id',
            ]
        ],
    ];

    /**
     * @title 接单
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:takeOrder desc:接单
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:lat type:string require:1 default:'' other:shr desc:经度
     * @param name:lng type:string require:1 default:'' other:shr desc:纬度
     *
     * @return data:[]
     */
    public function takeOrder()
    {
        $shipping_uid = $this->arr['uid'];
        $order_id = $this->arr['order_id'];
        $lat = $this->arr['lat'] ?? '';
        $lng = $this->arr['lng'] ?? '';

        //查询用户状态  登陆时已判断是否是捎货人 此处只判断是否被禁用
        if(!UserShaohuo::get(['uid' => $shipping_uid,'status' => 1]))return Fun::error(801029,'',0,['reason' => '您已被管理员禁止接单']);

        //查询订单详情
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id]);

        if(empty($order_info)){
            return Fun::error('801013');
        }

        if($order_info->status != 2){
            //无效订单
            return Fun::error('801019');
        }

        $fc_id = $order_info->fc_id;
        switch ($fc_id)
        {
            case 1:
                $status = 4;
                break;
            case 2:
                $status = 3;
                break;
            default:
                $status = 6;
        }

        //查询用户权限
        $rtn = UserShaohuoFuncs::get([
            'uid' => $shipping_uid,
            'fc_id' => $fc_id,
            'status' => 1,
            'user_status' => 1
        ]);

        if(empty($rtn)){
            //没有权限
            return Fun::error('801020');
        }

        Db::startTrans();
        try{
            //修改捎货人信息
            OrderInfoShaohuo::where([
                'order_id' => $order_id,
                'status' => 2
            ])->update([
                'shipping_uid' => $shipping_uid,
                'status' => $status
            ]);

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,4,$shipping_uid,'',$lat,$lng);
            Db::commit();
            return Fun::success('接单成功');
        }catch (ErrorException $exception){
            Db::rollback();
            return Fun::error('801021');
        }

    }

    /**
     * @title 取件
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:pickupOrder desc:取件
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:lat type:string require:1 default:'' other:shr desc:经度
     * @param name:lng type:string require:1 default:'' other:shr desc:纬度
     *
     * @return data:[]
     */
    public function pickupOrder()
    {
        $shipping_uid = $this->arr['uid'];
        $order_id = $this->arr['order_id'];
        $lat = $this->arr['lat'] ?? '';
        $lng = $this->arr['lng'] ?? '';

        //查询订单详情
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id]);
        $fc_id = $order_info->fc_id;

        //查询用户权限
        $rtn = UserShaohuoFuncs::get([
            'uid' => $shipping_uid,
            'fc_id' => $fc_id,
            'status' => 1,
            'user_status' => 1
        ]);

        if(empty($rtn)){
            //没有权限
            return Fun::error('801020');
        }

        Db::startTrans();
        try{
            //修改捎货人信息
            OrderInfoShaohuo::where([
                'order_id' => $order_id,
                'status' => 3
            ])->update([
                'shipping_uid' => $shipping_uid,
                'status' => 4
            ]);

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,5,$shipping_uid,'',$lat,$lng);
            Db::commit();
            return Fun::success('取件成功');
        }catch (ErrorException $exception){
            Db::rollback();
            return Fun::error('801022');
        }
    }

    /**
     * @title 送达
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:sendtoOrder desc:送达
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:lat type:string require:1 default:'' other:shr desc:经度
     * @param name:lng type:string require:1 default:'' other:shr desc:纬度
     *
     * @return data:[]
     */
    public function sendtoOrder()
    {
        $shipping_uid = $this->arr['uid'];
        $order_id = $this->arr['order_id'];
        $lat = $this->arr['lat'] ?? '';
        $lng = $this->arr['lng'] ?? '';

        //查询订单详情
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id]);
        $fc_id = $order_info->fc_id;

        //查询用户权限
        $rtn = UserShaohuoFuncs::get([
            'uid' => $shipping_uid,
            'fc_id' => $fc_id,
            'status' => 1,
            'user_status' => 1
        ]);

        if(empty($rtn)){
            //没有权限
            return Fun::error('801020');
        }

        Db::startTrans();
        if(!in_array($order_info->fc_id,[1,2])){
            try{
                OrderInfoShaohuo::where(['shipping_uid' => $shipping_uid,'order_id' => $order_id])->update(['status' => 8]);
                //添加路由信息
                ShaohuoOrderService::instance()->orderAction($order_id,8,$shipping_uid,'',$lat,$lng);
                Db::commit();
                return Fun::success([]);
            }catch (ErrorException $exception){
                Db::rollback();
                return Fun::error('');
            }
        }

        try{
            //修改捎货人信息
            OrderInfoShaohuo::where([
                'order_id' => $order_id,
                'status' => 4
            ])->update([
                'shipping_uid' => $shipping_uid,
                'status' => 5
            ]);

            //获得收益，失败回滚
            $rtn = UserBalanceRespository::addShipperIncome($shipping_uid,$order_id);
            if($rtn['code'] != 'success'){
                Db::rollback();
                return Fun::error('801023');
            }

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,6,$shipping_uid,'',$lat,$lng);
            Db::commit();
            return Fun::success('送达成功');
        }catch (ErrorException $exception){
            Db::rollback();
            return Fun::error('801023');
        }
    }

    /**
     * @title 捎货人业务列表
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:allowFuncs desc:捎货人业务列表
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     *
     * @return data:[]
     */
    public function allowFuncs()
    {
        $uid = $this->arr['uid'];
        $list = UserShaohuoFuncs::all([
            'uid' => $uid,
            'status' => 1,
        ]);
        foreach ($list as &$item){
            $item = $item->toArray();
        }
        return Fun::success($list);
    }

    /**
     * @title 捎货人修改业务接单状态
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:changeFuncStatus desc:捎货人修改业务接单状态
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:fc_id type:string require:1 default:'' other:shr desc:业务id
     * @param name:user_status type:string require:1 default:'' other:shr desc:业务接单状态1接单|0不接单
     *
     * @return data:[]
     */
    public function changeFuncStatus()
    {
        $uid = $this->arr['uid'];
        $fc_id = $this->arr['fc_id'];
        $user_status = $this->arr['user_status'];

        try{
            UserShaohuoFuncs::where([
                'uid' => $uid,
                'fc_id' => $fc_id
            ])->update(['user_status' => $user_status]);

            return Fun::success([],'修改成功');
        }catch (ErrorException $exception){
            return Fun::error('');
        }
    }


    /**
     * @title 保存经纬度
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:saveLocate desc:接单列表
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:lat type:string require:1 default:'' other:shr desc:经度
     * @param name:lng type:string require:1 default:'' other:shr desc:纬度
     *
     * @return data:[]
     */
    public function saveLocate()
    {
        $redis = new Redis();
        $hredis = $redis->handler();

        $uid = $this->arr['uid'];
        $lat = $this->arr['lat'];
        $lng = $this->arr['lng'];

        //获取地址id
        $region = BaiduMapService::instance()->getSiteCode($lat,$lng);
        $region_id = $region['adcode'];

        $user_redis = 'CACHE:USER:LOCATE:' . $uid;
        $region_redis = 'CACHE:REGION:USERS:' . $region_id;
        try{
            $hredis->zadd($region_redis,date('YmdHis'),$uid);
            $hredis->hset($user_redis,'region_id',$region_id);
            $hredis->hset($user_redis,'lat',$lat);
            $hredis->hset($user_redis,'lng',$lng);

            return Fun::success([],'保存成功');
        }catch (ErrorException $exception){
            return Fun::error('');
        }
    }

    /**
     * @title 接单列表
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:orderList desc:接单列表
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:lat type:string require:1 default:'' other:shr desc:经度
     * @param name:lng type:string require:1 default:'' other:shr desc:纬度
     * @param name:current_page type:string require:0 default:1 other:shr desc:当前页
     * @param name:per_page type:string require:0 default:10 other:shr desc:每页大小
     *
     * @return data:[]
     */
    public function orderList()
    {
        $uid = $this->arr['uid'];
        $lat = $this->arr['lat'];
        $lng = $this->arr['lng'];

        //查询用户状态  登陆时已判断是否是捎货人 此处只判断是否被禁用
        if(!UserShaohuo::get(['uid' => $uid,'status' => 1]))return Fun::error(801029,'',0,['reason' => '您已被管理员禁止接单']);

        $current_page = empty($this->arr['current_page']) ? 1 : $this->arr['current_page'];
        $per_page = empty($this->arr['per_page']) ? 10 : $this->arr['per_page'];
        $paginate = [
            'page' => $current_page,
        ];

        $region = BaiduMapService::instance()->getSiteCode($lat,$lng);

        $region_id = $region['adcode'];

        $list = UserShaohuoFuncs::all([
            'uid' => $uid,
            'status' => 1,
            'user_status' => 1
        ]);
        $fc_ids = [];
        foreach ($list as $item){
            $fc_ids[] = $item->fc_id;
        }

        if(empty($fc_ids)){
            return Fun::success([]);
        }

//        $time = date('Y-m-d H:i:s',strtotime('+5 minute'));
        $order_list = OrderInfoShaohuo::where([
            'region_id' => $region_id,
            'status' => 2
        ])
//            ->where("book_time > '$time'")
            ->where("fc_id in (".implode(',',$fc_ids).")")
            ->order('id desc')
            ->paginate(intval($per_page),false,$paginate);

        $destinations = [];
        foreach ($order_list as $item){

            $des = [];
            if($item->fc_id == 1){

                $addr = $item->end_addr;
            }elseif ($item->fc_id == 2){
                $addr = $item->start_addr;
            }else{
                $addr = $item->serve_addr;
            }
            $addr = json_decode($addr,true);
            $des['lat'] = $addr['lat'];
            $des['lng'] = $addr['lng'];

            $destinations[] = $des;
        }

        $origins[0]['lat'] = $lat;
        $origins[0]['lng'] = $lng;
        $rtn = BaiduMapService::instance()->getDistances($origins,$destinations);

        $list = [];
        foreach ($order_list as $key=>$value){
            $info = [];
            $info['order_id'] = $value->order_id;
            $info['item_name'] = $value->item_name;
            $info['video_time'] = $value->video_time;
            $info['fc_id'] = $value->fc_id;
            $info['book_time'] = $value->book_time;
            $info['book_time_str'] = ShippingService::instance()->getTimeStr($value->book_time);
            $info['shipping_fee'] = sprintf("%.2f",$value->shipping_fee / 100);
            $info['remark'] = $value->remark;
            $info['apart'] = $rtn[$key]['distance'];
            $info['distance'] = $value->distance;
            $info['start_addr'] = '';
            $info['end_addr'] = '';
            $info['serve_addr'] = '';

            //发件人
            $start_addr = json_decode($value->start_addr,true);
            if($start_addr){
                $info['start_addr'] = $start_addr ? $start_addr['province'] . $start_addr['city'] . $start_addr['district'].$start_addr['address'].$start_addr['building'] : '';
            }

            //收件人
            $end_addr = json_decode($value->end_addr,true);
            if($end_addr){
                $info['end_addr'] = $end_addr ? $end_addr['province'] . $end_addr['city'] . $end_addr['district'].$end_addr['address'].$end_addr['building'] : '';
            }

            //发布人
            $serve_addr = json_decode($value->serve_addr,true);
            if($serve_addr){
                $info['serve_addr'] = $serve_addr ? $serve_addr['province'] . $serve_addr['city'] . $serve_addr['district'].$serve_addr['address'].$serve_addr['building'] : '';
            }

            $list[] = $info;
        }

        $rtn = [];
        $rtn['data'] = $list;
        $rtn['total'] = $order_list->total();
        $rtn['per_page'] = $per_page;
        $rtn['current_page'] = $current_page;
        $rtn['last_page'] = $order_list->lastPage();

        return Fun::success($rtn);
    }

    /**
     * @title 待办列表
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:unDoneList desc:待办列表
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:current_page type:string require:0 default:1 other:shr desc:当前页
     * @param name:per_page type:string require:0 default:10 other:shr desc:每页大小
     *
     * @return data:[]
     */
    public function unDoneList()
    {
        $uid = $this->arr['uid'];

        $current_page = empty($this->arr['current_page']) ? 1 : $this->arr['current_page'];
        $per_page = empty($this->arr['per_page']) ? 10 : $this->arr['per_page'];
        $paginate = [
            'page' => $current_page,
        ];

        $order_list = OrderInfoShaohuo::where([
            'shipping_uid' => $uid,
        ])
            ->where('((status = 3 or status = 4) and (fc_id = 1 or fc_id = 2)) or (fc_id > 2 and status = 6)')
            ->paginate(intval($per_page),false,$paginate)->toArray();

        $list = [];
        foreach ($order_list['data'] as $item){

            $info = [];
            $info['order_id'] = $item['order_id'];
            $info['order_num'] = $item['order_num'];
            $info['fc_id'] = $item['fc_id'];
            $info['item_name'] = $item['item_name'];
            $info['video_time'] = $item['video_time'];
            $info['book_time_str'] = ShippingService::instance()->getTimeStr($item['book_time']);
            $info['start_addr'] = '';
            $info['end_addr'] = '';
            $info['serve_addr'] = '';
            $info['create_time'] = $item['create_time'];
            $info['status'] = $item['status'];
            $info['remark'] = $item['remark'];

            //发件人
            $start_addr = json_decode($item['start_addr'],true);
            if($start_addr){
                $info['start_addr'] = $start_addr ? $start_addr['province'] . $start_addr['city'] . $start_addr['district'].$start_addr['address'].$start_addr['building'] : '';
            }

            //收件人
            $end_addr = json_decode($item['end_addr'],true);
            if($end_addr){
                $info['end_addr'] = $end_addr ? $end_addr['province'] . $end_addr['city'] . $end_addr['district'].$end_addr['address'].$end_addr['building'] : '';
            }

            //发布人
            $serve_addr = json_decode($item['serve_addr'],true);
            if($serve_addr){
                $info['serve_addr'] = $serve_addr ? $serve_addr['province'] . $serve_addr['city'] . $serve_addr['district'].$serve_addr['address'].$serve_addr['building'] : '';
            }

            if($item['fc_id'] == 1 && $item['status'] == 3){
                $info['name'] = $start_addr['consignee'];
                $info['mobile'] = $start_addr['mobile'];
            }elseif($item['fc_id'] == 1 || $item['fc_id'] == 2){
                $info['name'] = $end_addr['consignee'];
                $info['mobile'] = $end_addr['mobile'];
            }else{
                $info['name'] = $serve_addr['consignee'];
                $info['mobile'] = $serve_addr['mobile'];
            }

            $list[] = $info;
        }
        $order_list['data'] = $list;

        return Fun::success($order_list);
    }

    /**
     * @title 完成订单列表
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:doneList desc:完成订单列表
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:type type:string require:1 default:'1' other:shr desc:类型1所有订单|2当日订单
     * @param name:current_page type:string require:0 default:1 other:shr desc:当前页
     * @param name:per_page type:string require:0 default:10 other:shr desc:每页大小
     *
     * @return data:[]
     */
    public function doneList()
    {
        //组织查询条件
        $data['shipping_uid'] = $this->arr['uid'];
        $type = empty($this->arr['type']) ? 1 : $this->arr['type'];

        $str = '1=1';
        if($type != 1){
            $str = "a.create_time >= '" .date('Y-m-d') ."'";
        }

        $current_page = empty($this->arr['current_page']) ? 1 : $this->arr['current_page'];
        $per_page = empty($this->arr['per_page']) ? 10 : $this->arr['per_page'];
        $paginate = [
            'page' => $current_page,
        ];

        $info = Db::table('sh_order_info_shaohuo')
            ->alias('i')
            ->join('sh_order_action_shaohuo a','i.order_id = a.order_id')
            ->where('((i.status = 5 or i.status = 6) and (i.fc_id = 1 or i.fc_id = 2)) or (i.fc_id > 2 and i.status = 8)')
            ->where('i.shipping_uid = '.$this->arr['uid'])
            ->where('a.type = 6 or a.type = 8')
            ->where($str)
            ->paginate(intval($per_page),false,$paginate)
            ->toArray();

        //处理数据
        $list = [];
        foreach ($info['data'] as $item){
            $value = [];

            $value['start_user'] = '';
            $value['end_user'] = '';
            $value['order_id'] = $item['order_id'];
            $value['func_id'] = $item['fc_id'];
            $value['func_name'] = $item['func_name'];
            $value['order_num'] = $item['order_num'];
            $value['operate_time'] = $item['create_time'];
            $value['item_name'] = $item['item_name'];
            $value['shipping_fee'] = sprintf("%.2f",$item['shipping_fee'] / 100);
            $value['status'] = $item['status'];
            $value['video_time'] = $item['video_time'];

            //发件人收件人
            if($start_addr = json_decode($item['start_addr'])){
                $value['start_user'] = $start_addr->consignee ? $start_addr->consignee : $start_addr->mobile;
            }
            if($end_addr = json_decode($item['end_addr'])){
                $value['end_user'] = $end_addr->consignee ? $end_addr->consignee : $end_addr->mobile;
            }

            $value['order_action'] = $order_action ?? '';

            //捎货人手机号
            $value['shipping_user_mobile'] = User::get($item['shipping_uid'])->mobile ?? '';

            $list[] = $value;
        }

        $info['data'] = $list;

        return Fun::success($info);
    }

    /**
     * @title 取消订单
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:cancelOrder desc:取消订单
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:cancel_reason type:string require:0 default:'' other:shr desc:取消原因
     * @param name:order_id type:string require:1 default: other: desc:订单id
     * @param name:lat type:string require:1 default:'' other:shr desc:经度
     * @param name:lng type:string require:1 default:'' other:shr desc:纬度
     *
     * @return data:[]
     */
    public function cancelOrder()
    {
        $order_id = $this->arr['order_id'];
        $uid = $this->arr['uid'];
        $lat = $this->arr['lat'] ?? '';
        $lng = $this->arr['lng'] ?? '';
        $cancel_reason = empty($this->arr['cancel_reason']) ? '' : $this->arr['cancel_reason'];
        //查询订单信息
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id,'shipping_uid' => $uid]);
        if(!$order_info){
            return Fun::error('801013');
        }

        if(empty($order_info)){
            return Fun::error('801013');
        }

        Db::startTrans();
        try{
            if($order_info->fc_id == 1 && $order_info->status == 4){
                //退款逻辑
                FoundService::instance()->drawBack($order_info->order_id);
                Order::where(['id' => $order_info->order_id])->update(['status' => 4]);
                OrderInfoShaohuo::where(['order_id' => $order_info->order_id])->update(['status' => 7,'cancel_reason'=>$cancel_reason]);
            }elseif ($order_info->fc_id == 2 &&  $order_info->status == 3){
                //退款逻辑
                FoundService::instance()->drawBack($order_info->order_id);
                Order::where(['id' => $order_info->order_id])->update(['status' => 4]);
                OrderInfoShaohuo::where(['order_id' => $order_info->order_id])->update(['status' => 7,'cancel_reason'=>$cancel_reason]);
            }elseif ($order_info->fc_id > 2 && $order_info->status == 6){
                Order::where(['id' => $order_info->order_id])->update(['status' => 3]);
                OrderInfoShaohuo::where(['order_id' => $order_info->order_id])->update(['status' => 7,'cancel_reason'=>$cancel_reason]);
            }else{
                Db::rollback();
                //禁止取消
                return Fun::error('801011');
            }

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,3,$uid,'',$lat,$lng);

            Db::commit();
            return Fun::success([],'取消成功');
        }catch (ErrorException $exception){
            Db::rollback();
            //取消失败
            return Fun::error('801012');
        }
    }

    /**
     * @title 捎货人业绩
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:achievement desc:捎货人业绩
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     *
     * @return data:[]
     */
    public function achievement()
    {
        //组织查询条件
        $data['shipping_uid'] = $this->arr['uid'];
        $str = "a.create_time >= '" .date('Y-m-d') ."'";

        $total_income = OrderInfoShaohuo::field('sum(shipping_fee) as sumfee')
            ->where('shipping_uid = '.$this->arr['uid'])
            ->where('status = 5 or status = 6')
            ->find();
        $total_income = sprintf("%.2f",($total_income->sumfee ?? 0) / 100);

        $total_orders = Db::table('sh_order_info_shaohuo')
            ->alias('i')
            ->join('sh_order_action_shaohuo a','i.order_id = a.order_id')
            ->where('((i.status = 5 or i.status = 6) and (i.fc_id = 1 or i.fc_id = 2)) or (i.fc_id > 2 and i.status = 8)')
            ->where('i.shipping_uid = '.$this->arr['uid'])
            ->where('a.type = 6 or a.type = 8')
            ->count();

        $today_orders = Db::table('sh_order_info_shaohuo')
            ->alias('i')
            ->join('sh_order_action_shaohuo a','i.order_id = a.order_id')
            ->where('((i.status = 5 or i.status = 6) and (i.fc_id = 1 or i.fc_id = 2)) or (i.fc_id > 2 and i.status = 8)')
            ->where('i.shipping_uid = '.$this->arr['uid'])
            ->where('a.type = 6 or a.type = 8')
            ->where($str)->count();

        $data = [
            'total_income' => $total_income,
            'total_orders' => $total_orders,
            'today_orders' => $today_orders
        ];

        return Fun::success($data);
    }

    /**
     * @title 开关捎货人业务
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:changeTakingStatus desc:开关捎货人业务
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     * @param name:type type:string require:1 default:'' other:shr desc:类型1所有业务2基础业务
     * @param name:status type:string require:1 default:'' other:shr desc:接单状态1开启2关闭
     *
     * @return data:[]
     */
    public function changeTakingStatus()
    {
        $uid = $this->arr['uid'];
        $type = $this->arr['type'];
        $taking_status = $this->arr['status'];

        //查询用户状态  登陆时已判断是否是捎货人 此处只判断是否被禁用
        if(!UserShaohuo::get(['uid' => $uid,'status' => 1]))return Fun::error(801029,'',0,['reason' => '您已被管理员禁止接单']);

        try{
            if($type == 1){
                UserShaohuo::where(['uid' => $uid])->update(['taking_status' => $taking_status]);
            }else{
                UserShaohuoFuncs::where(['uid' => $uid])->where('fc_id =1 or fc_id = 2')->update(['user_status' => $taking_status]);
            }
            return Fun::success([]);
        }catch (ErrorException $exception){
            return Fun::error('');
        }
    }

    /**
     * @title 捎货人基础信息
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Shipping desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:baseInfo desc:捎货人基础信息
     * @param name:token type:string require:1 default: other: desc:捎货人APPtoken
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:app_name type:string require:1 default:'' other:shr desc:客户端名称，捎货人app必传shr
     *
     * @return data:[]
     */
    public function baseInfo()
    {
        $uid = $this->arr['uid'];

        //查询用户状态  登陆时已判断是否是捎货人 此处只判断是否被禁用
        if(!UserShaohuo::get(['uid' => $uid,'status' => 1]))return Fun::error(801029,'',0,['reason' => '您已被管理员禁止接单']);

        $user_shaohuo = UserShaohuo::get(['uid' => $uid]);
        if(empty($user_shaohuo)){
            return Fun::error('');
        }
        $taking_status = $user_shaohuo->taking_status;

        //查询用户业务 如果有开启帮买或帮送业务 判定开启基础业务
        $user_funcs = UserShaohuoFuncs::where(['uid' => $uid,'user_status' => 1])
            ->where('fc_id = 1 or fc_id = 2')
            ->find();
        if(empty($user_funcs)){
            $user_status = 2;
        }else{
            $user_status = 1;
        }

        $data['taking_status'] = $taking_status;
        $data['user_status'] = $user_status;

        return Fun::success($data);

    }
}